<template>
  <div>
    <el-card>
      <el-row>
        <el-button type="primary" :icon="Plus" @click="toAdd()" v-button="['api:design:designtable:create']">
          新增
        </el-button>
      </el-row>
      <el-row>
        <el-table :data="tableList" :border="true" :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
          <el-table-column prop="name" label="表名称">
            <template #default="{ row }">
              {{ row.name }}
              <el-button text type="primary" :icon="EditPen" @click="renameTable(row.name)">重命名</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="表描述" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" :icon="EditPen" @click="toEdit(scope.row)"
                v-button="['api:design:designtable:update']">
                编辑
              </el-button>
              <el-popconfirm title="确定要删除这条数据?" @confirm="toDelete(scope.row)">
                <template #reference>
                  <el-button type="danger" :icon="Delete" v-button="['api:design:designtable:delete']">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-card>

    <!-- 修改表名弹框 -->
    <el-dialog :title="'修改表名'" v-model="dialogRenameTable">
      <el-form :label-width="'auto'" :model="renameTableForm" ref="renameTableFormRef">
        <el-form-item label="原表名" prop="oldTableName">
          <el-text>{{ renameTableForm.oldTableName }}</el-text>
        </el-form-item>
        <el-form-item label="新表名" prop="newTableName" :rules="[{
          required: true,
          message: '请输入新表名',
          trigger: ['blur', 'change'],
        }]">
          <el-input placeholder="请输入新表名" v-model="renameTableForm.newTableName">
            <template #prepend>
              {{ designPrefixConst }}
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="() => { dialogRenameTable = false }">取消</el-button>
          <el-button type="primary" @click="saveRenameTableForm(renameTableFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增，修改弹框 -->
    <el-dialog v-model="dialogVisible" :title="editTitle" :width="1000">
      <el-form :model="formData" ref="formDataRef" label-width="auto">
        <el-form-item label=" 表名" prop="name">
          <el-input v-model="formData.name" v-if="editType === EditEnum.create">
            <template #prepend>
              {{ designPrefixConst }}
            </template>
          </el-input>
          <template v-else>
            <el-text>{{ formData.name }}</el-text>
          </template>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="列信息">
          <el-button type="primary" :icon="Plus" @click="addColumnRow()">
            添加列
          </el-button>
          <el-table :data="formData.columnList" :border="true"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
            <el-table-column prop="columnDescription" label="列描述">
              <template #default="{ row, $index }">
                <el-icon v-if="row.isPrimarykey">
                  <Key />
                </el-icon>
                <el-input :size="'small'" v-model="row.columnDescription" v-if="editRowIndex === $index" />
                <template v-else>{{ row.columnDescription }}</template>
              </template>
            </el-table-column>
            <el-table-column prop="columnName" label="列名称">
              <template #default="{ row, $index }">
                <el-input :size="'small'" v-model="row.columnName" v-if="editRowIndex === $index" />
                <template v-else>{{ row.columnName }}</template>
              </template>
            </el-table-column>
            <el-table-column prop="dataType" label="数据类型">
              <template #default="{ row, $index }">
                <el-select :size="'small'" v-model="row.dataType" v-if="editRowIndex === $index">
                  <el-option v-for="item in dataTypeList" :label="`${item.code}(${item.description})`"
                    :value="item.code" />
                </el-select>
                <template v-else>{{ row.dataType }}</template>
              </template>
            </el-table-column>
            <el-table-column prop="length" label="长度">
              <template #default="{ row, $index }">
                <el-input-number :size="'small'" controls-position="right" v-model="row.length"
                  v-if="editRowIndex === $index && row.dataType === 'nvarchar'" />
                <template v-else>{{ row.length }}</template>
              </template>
            </el-table-column>
            <el-table-column prop=" decimalDigits" label="小数位数">
              <template #default="{ row, $index }">
                <el-input-number :size="'small'" controls-position="right" v-model="row.decimalDigits"
                  v-if="editRowIndex === $index && row.dataType === 'decimal'" />
                <template v-else>{{ row.decimalDigits }}</template>
              </template>
            </el-table-column>
            <el-table-column :width="70" prop="isNullable" label="可空">
              <template #default="{ row, $index }">
                <el-switch :size="'small'" v-model="row.isNullable" :disabled="editRowIndex != $index" />
              </template>
            </el-table-column>
            <el-table-column :min-width="90" label="操作">
              <template #default="{ row, $index }">
                <template v-if="editRowIndex === $index">
                  <el-button type="primary" :size="'small'" link @click="saveColumn(row)">确定</el-button>
                  <el-button type="primary" :size="'small'" link @click="cancelColumn">取消</el-button>
                </template>
                <el-button type="primary" link @click="() => { editRowIndex = $index }" v-else>编辑</el-button>
                <el-popconfirm title="确定要删除这条数据?" @confirm="removeColumn(row, $index)">
                  <template #reference>
                    <el-button type="danger" link>删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit(formDataRef)">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import DesignTableApi, { DesignColumnDataType, DesignColumnModel, DesignTableEdit, DesignTableModel, DesignTableRename } from '@/api/design/designTable';
import { Plus, Delete, EditPen, Search, Promotion } from "@element-plus/icons-vue";
import successMsg from '@/utils/successMsg';
import { FormInstance } from 'element-plus';
import { EditEnum } from '@/enums/EditEnum';

// 表前缀
const designPrefixConst = ref('Design_Instance_');

const tableList = ref<DesignTableModel[]>([]);

onMounted(async () => {
  await query();
});

const query = async () => {
  const dataList = await DesignTableApi.query();
  tableList.value = dataList;
}

const dataTypeList = ref<DesignColumnDataType[]>([]);
const queryDataType = async () => {
  const data = await DesignTableApi.queryDataTypeSelect();
  dataTypeList.value = data;
}

// 表重命名
const renameTableFormRef = ref<FormInstance>();
const renameTableForm = ref<DesignTableRename>({});
const dialogRenameTable = ref(false);
const renameTable = (tableName: string) => {
  renameTableForm.value.oldTableName = tableName;
  dialogRenameTable.value = true;
}

const saveRenameTableForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const { success, message } = await DesignTableApi.tableRename(renameTableForm.value);
      successMsg(success, message, async () => {
        await query();
        dialogRenameTable.value = false;
      });
    }
  })
}

const dialogVisible = ref(false);
const editType = ref<EditEnum>();
const editTitle = ref<string>();
const toAdd = async () => {
  dialogVisible.value = true;
  editTitle.value = "新增表";
  formData.value = { columnList: [] };
  await queryDataType();
  editType.value = EditEnum.create;
}

const formDataRef = ref<FormInstance>();
const formData = ref<DesignTableEdit>({});

const toEdit = async (row: DesignTableModel) => {
  dialogVisible.value = true;
  editTitle.value = "修改表";
  await queryDataType();
  editType.value = EditEnum.update;
  formData.value.name = row.name;
  formData.value.description = row.description;
  const data = await DesignTableApi.queryColumn(row.name);
  data.forEach(x => x.oldColumnName = x.columnName);
  formData.value.columnList = data;
}

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      formData.value.columnList.forEach(x => {
        if (x.columnName === x.oldColumnName) {
          x.oldColumnName = null;
        }
      });
      const { success, message } = await DesignTableApi[EditEnum[editType.value]](formData.value);
      successMsg(success, message, async () => {
        await query();
        dialogVisible.value = false;
        formDataRef.value.resetFields();
      });
    }
  })
}

const toDelete = async (row: DesignTableModel) => {
  const { success, message } = await DesignTableApi.delete(row.name);
  successMsg(success, message, await query());
}

const editRowIndex = ref<number>(null);
const addColumnRow = () => {
  formData.value.columnList.push({})
  editRowIndex.value = formData.value.columnList.length - 1;
}

const saveColumn = async (row: DesignColumnModel) => {
  editRowIndex.value = null;
}

const removeColumn = async (row: DesignColumnModel, index: number) => {
  formData.value.columnList.splice(index, 1);
  editRowIndex.value = null;
}

const cancelColumn = async () => {
  editRowIndex.value = null;
}


</script>

<style lang="scss" scoped></style>
